from rest_framework import serializers
from rest_framework.viewsets import ModelViewSet
from labor_price.models import Log
import json
from rest_framework.decorators import action
from rest_framework.response import Response
from django.http import JsonResponse


class LogSerializer(serializers.ModelSerializer):
    class Meta:
        model = Log
        fields = '__all__'


class LogView(ModelViewSet):
    queryset = Log.objects.all()  # 查询集
    serializer_class = LogSerializer  # 序列化器

    @action(methods=['get'], detail=False)
    def batch_del(self, request):
        print(request.GET.get('del_list'))
        return Response({'msg': "批量删除成功", 'code': 200})

    @action(methods=['get'], detail=False)
    def batch_del(self, request):
        del_list = request.GET.get('del_list')
        del_list = json.loads(del_list)
        try:
            for i in (del_list):
                Log.objects.get(id=i).delete()
        except:
            return Response({'msg': "批量删除失败", 'code': 400, 'data': '存在关联数据；不允许删除'})
        return Response({'msg': "批量删除成功", 'code': 200})


def logSelete(req):
    if req.method == 'GET':
        page = int(req.GET.get("page"))
        pageSize = int(req.GET.get("pageSize"))
        star = (page-1) * pageSize
        end = page * pageSize
        data = list(Log.objects.all().values()[star: end])
        cou = Log.objects.count()
        return JsonResponse({"code": 200, "list": data, "msg": "请求成功", "total": cou})
    else:
        return JsonResponse({"code": 400, "msg": "请求方式错误"})

